package com.example.rabbitmqbootproducer.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * mq配置
 *
 * @author 伯路平
 * @since 2023/6/20
 **/
@Configuration
@Slf4j
public class RabbitConfig {
    @Bean
    public RabbitTemplate getRabbitTemplateInstance(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        // 设置mandatory,才能触发回调函数，无论推送结果怎样都会强制调用回调函数
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback((correlationData, b, s) -> {
            log.info("confirmCallback--->相关数据：{}", correlationData);
            log.info("confirmCallback--->确认情况：{}", b);
            log.info("confirmCallback--->原因：{}", s);
        });
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            log.info("returnedMessage-->消息：{}", returnedMessage.getMessage());
            log.info("returnedMessage-->回应码：{}", returnedMessage.getReplyCode());
            log.info("returnedMessage-->回应消息：{}", returnedMessage.getReplyText());
            log.info("returnedMessage-->交换机：{}", returnedMessage.getExchange());
            log.info("returnedMessage-->路由键：{}", returnedMessage.getRoutingKey());
        });
        return rabbitTemplate;
    }
}
